<!-- CreateRecord.vue -->
<template>
    <div class="min-h-screen bg-gray-100 flex justify-center items-center">
        <div class="bg-white p-8 shadow-lg rounded-lg w-[25vw]">
            <!-- 患者信息展示区域 -->
            <div class="mb-8 border-b border-gray-200 pb-6">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">创建检测记录</h2>
                <div class="space-y-2 text-gray-600">
                    <div class="flex items-center">
                        <span class="w-[25%] font-medium">姓名：</span>
                        <span class="text-gray-800">{{ record.name }}</span>
                    </div>
                    <div class="flex items-center">
                        <span class="w-[25%] font-medium">手机号：</span>
                        <span class="text-gray-800">{{ record.phone }}</span>
                    </div>
                    <div class="flex items-center">
                        <span class="w-[25%] font-medium">年龄：</span>
                        <span class="text-gray-800">{{ record.age }}</span>
                    </div>
                    <div class="flex items-center">
                        <span class="w-[25%] font-medium">性别：</span>
                        <span class="text-gray-800">{{ record.sex }}</span>
                    </div>
                </div>
            </div>
            <div class="space-y-4">
                <var-button v-if="!isBloodRoutine" :loading="loading" @click="show = true" type="primary" block class="transform transition duration-300 hover:scale-105 hover:shadow-lg">上传血常规指标数据</var-button>
                <var-button v-else type="primary" block>血常规指标数据已提交</var-button>
                <var-button v-if="!isBloodSmear" :loading="bloodloading" @click="bloodshow = true" type="info" block class="transform transition duration-300 hover:scale-105 hover:shadow-lg">上传血涂片图像</var-button>
                <var-button v-else type="info" block>血涂片图像已上传</var-button>
                <var-button @click="createRecord" type="success" block class="transform transition duration-300 hover:scale-105 hover:shadow-lg">提交检测记录</var-button>
                <var-button @click="$emit('back')" type="warning" block class="transform transition duration-300 hover:scale-105 hover:shadow-lg">返回</var-button>
            </div>
            <!-- 数据上传弹窗 -->
            <var-popup v-model:show="show" class="w-[35vw] p-6 rounded-lg">
                <var-loading description="LOADING" color="#006263" :loading="loading">
                    <var-form ref="form">
                        <h2 class="text-xl font-semibold text-gray-800 mb-4">上传血常规指标数据</h2>
                        <div class="grid grid-cols-2 gap-6">
                            <var-input v-model="uploadData.RBC" type="number" focus-color="#006263" placeholder="请输入 RBC" :rules="[(v) => !!v || 'RBC不能为空']" />
                            <var-input v-model="uploadData.HGB" type="number" focus-color="#006263" placeholder="请输入 HGB" :rules="[(v) => !!v || 'HGB不能为空']" />
                            <var-input v-model="uploadData.HCT" type="number" focus-color="#006263" placeholder="请输入 HCT" :rules="[(v) => !!v || 'HCT不能为空']" />
                            <var-input v-model="uploadData.MCV" type="number" focus-color="#006263" placeholder="请输入 MCV" :rules="[(v) => !!v || 'MCV不能为空']" />
                            <var-input v-model="uploadData.MCH" type="number" focus-color="#006263" placeholder="请输入 MCH" :rules="[(v) => !!v || 'MCH不能为空']" />
                            <var-input v-model="uploadData.MCHC" type="number" focus-color="#006263" placeholder="请输入 MCHC" :rules="[(v) => !!v || 'MCHC不能为空']" />
                            <var-input v-model="uploadData.RDW" type="number" focus-color="#006263" placeholder="请输入 RDW-SD" :rules="[(v) => !!v || 'RDW-SD不能为空']" />
                            <div class="flex items-end justify-end">
                                <var-button color="#006263" text-color="#fff" block @click="handleConfirm">确定上传</var-button>
                            </div>
                        </div>
                    </var-form>
                </var-loading>
            </var-popup>
            <!-- 血涂片上传弹窗 -->
            <var-popup v-model:show="bloodshow" class="w-[35vw] h-[53vh] p-6 rounded-lg">
                <var-loading description="LOADING" color="#006263" :loading="bloodloading">
                    <div class="flex flex-col h-full">
                        <h2 class="text-xl font-semibold text-gray-800 mb-4">上传血涂片图像</h2>
                        <div class="border-2 border-[#006263] rounded-lg h-[30vh] p-4 overflow-auto">
                            <var-uploader v-model="files" type="file" maxlength="5" multiple :maxsize="1000000" accept="image/*">
                                <Icon type="plus" size="60" color="#006263"></Icon>
                            </var-uploader>
                        </div>
                        <div class="flex mt-[5vh] h-[5vh] justify-center items-center">
                            <div class="w-[50%]">
                                <var-button color="#006263" text-color="#fff" block @click="handleUpload">上传血涂片</var-button>
                            </div>
                        </div>
                    </div>
                </var-loading>
            </var-popup>
        </div>
        <var-dialog message="是否查看检测结果？" confirm-button-text-color="#006263" cancel-button-text-color="#006263" v-model:show="recordShow" @confirm="createRecord" />
    </div>
</template>

<script>
import { toRaw } from 'vue';
export default {
    data() {
        return {
            show: false,
            recordShow: false,
            loading: false,
            bloodshow: false,
            bloodloading: false,
            isBloodRoutine: false,
            isBloodSmear: false,
            files: [],
            uploadData: {
                recordId: this.$store.record.recordId,
                patientId: this.$store.record.patientId,
                RBC: '',
                HGB: '',
                HCT: '',
                MCV: '',
                MCH: '',
                MCHC: '',
                RDW: ''
            }
        };
    },
    mounted() {
        if (Object.keys(this.record.bloodDrooping).length) {
            this.isBloodRoutine = true;
        }
        if (Object.keys(this.record.imgDetail).length) {
            this.isBloodSmear = true;
        }
    },
    computed: {
        record() {
            return this.$store.record;
        }
    },
    methods: {
        async handleConfirm() {
            const valid = await this.$refs.form.validate();
            if (!valid) {
                this.$api.notify.error('表单验证失败，请检查输入');
                return;
            }
            this.loading = true;
            const res = await this.$api.record.uploadBloodRoutineIndicators(this.uploadData);
            this.loading = false;
            if (res.success) {
                this.$api.notify.success('血常规指标数据上传成功');
                this.uploadData.createdAt = new Date().toISOString();
                const uploadDataWithRename = { ...this.uploadData };
                uploadDataWithRename['RDW-SD'] = uploadDataWithRename.RDW;
                delete uploadDataWithRename.RDW;
                const bloodData = {
                    history: res.data.history.concat(uploadDataWithRename),
                    PredictedProbability: res.data.PredictedProbability
                };
                this.$store.record.bloodDrooping = bloodData;
                this.isBloodRoutine = true;
                this.show = false;
                if (this.isBloodSmear) {
                    this.recordShow = true;
                }
            } else {
                this.$api.notify.error('上传失败');
            }
        },
        async handleUpload() {
            if (this.files.length === 0) {
                this.$api.notify.error('请选择文件');
                return;
            }
            const formData = new FormData();
            const rawFiles = toRaw(this.files); // 解除响应式代理
            // 处理文件数据结构
            if (Array.isArray(rawFiles)) {
                rawFiles.forEach((fileObj) => {
                    // 检查是否存在file属性（根据VarUploader的实际数据结构）
                    if (fileObj.file instanceof File) {
                        formData.append('files', fileObj.file);
                    } else if (fileObj instanceof File) {
                        // 如果直接是File对象
                        formData.append('files', fileObj);
                    }
                });
            } else {
                // 处理单文件情况
                if (rawFiles.file instanceof File) {
                    formData.append('files', rawFiles.file);
                } else if (rawFiles instanceof File) {
                    formData.append('files', rawFiles);
                }
            }
            formData.append('patientId', this.uploadData.patientId);
            formData.append('recordId', this.uploadData.recordId);
            this.bloodloading = true;
            const res = await this.$api.record.uploadBloodSmearImages(formData);
            this.bloodloading = false;
            if (res.success) {
                this.$api.notify.success('血涂片图像上传成功');
                this.isBloodSmear = true;
                this.bloodshow = false;
                this.$store.record.imgDetail = res.data;
                if (this.isBloodRoutine) {
                    this.recordShow = true;
                }
            } else {
                this.$api.notify.error(res.error || '上传失败');
            }
        },
        async createRecord() {
            if (!this.isBloodRoutine || !this.isBloodSmear) {
                this.$api.notify.error('请先上传血常规指标数据和血涂片图像');
                return;
            }
            const PredictedProbability = this.$store.record.bloodDrooping.PredictedProbability;
            const imgDetails = this.$store.record.imgDetail;

            // 提取所有 imgProbability 对象
            const imgProbabilities = imgDetails.map((item) => item.imgProbability);
            // 初始化平均值对象
            const averageProbability = {
                地中海贫血: 0,
                正常: 0,
                缺铁性贫血: 0
            };

            // 计算每个键的总和
            imgProbabilities.forEach((prob) => {
                for (const key in averageProbability) {
                    averageProbability[key] += prob[key];
                }
            });

            // 计算平均值
            for (const key in averageProbability) {
                averageProbability[key] /= imgProbabilities.length;
            }
            // 按照权重计算最终概率
            const finalProbability = {
                地中海贫血: averageProbability['地中海贫血'] * 0.7 + PredictedProbability['地中海贫血'] * 0.3,
                正常: averageProbability['正常'] * 0.7 + PredictedProbability['正常'] * 0.3,
                缺铁性贫血: averageProbability['缺铁性贫血'] * 0.7 + PredictedProbability['缺铁性贫血'] * 0.3
            };
            this.$store.record.probability = finalProbability;
            this.$store.record.isShow = true;
        }
    }
};
</script>
